package main

import (
	"context"
	"k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/tools/clientcmd"
	"log"
	"time"
)

func main() {
	k8s, err := NewClientK8s()
	if err != nil {
		log.Printf("faild to init k8s client err, %v\n", err)
		return
	}
	log.Println("start to test k8s api")
	k8sApiTest(k8s)
	log.Println("finish to test k8s api")
	time.Sleep(100 * time.Second)
}

func k8sApiTest(k8s *ClientK8s) {
	if _, err := k8s.GetNodeList(); err != nil {
		log.Printf("failed to get node list, err: %v\n", err)
	} else {
		log.Println("success to get node list")
	}

	if _, err := k8s.GetNode("k8s-node1"); err != nil {
		log.Printf("failed to get node, err: %v\n", err)
	} else {
		log.Println("success to get node")
	}

	if _, err := k8s.GetPodList("default"); err != nil {
		log.Printf("failed to get pod list, err: %v\n", err)
	} else {
		log.Println("success to get pod list")
	}
}

// ClientK8s include ClientK8sSet & nodeName & configmap name
type ClientK8s struct {
	Clientset kubernetes.Interface
}

// NewClientK8s create k8s client
func NewClientK8s() (*ClientK8s, error) {
	clientCfg, err := clientcmd.BuildConfigFromFlags("", "")
	if err != nil {
		log.Printf("clientCfg err, %v\n", err)
		return nil, err
	}

	client, err := kubernetes.NewForConfig(clientCfg)
	if err != nil {
		log.Printf("client err, %v\n", err)
		return nil, err
	}

	return &ClientK8s{Clientset: client}, nil
}

func (ki *ClientK8s) GetNodeList() (*v1.NodeList, error) {
	return ki.Clientset.CoreV1().Nodes().List(context.Background(), metav1.ListOptions{})
}

func (ki *ClientK8s) GetNode(name string) (*v1.Node, error) {
	return ki.Clientset.CoreV1().Nodes().Get(context.Background(), name, metav1.GetOptions{})
}

func (ki *ClientK8s) GetPodList(ns string) (*v1.PodList, error) {
	return ki.Clientset.CoreV1().Pods(ns).List(context.Background(), metav1.ListOptions{})
}
